<script setup lang="ts">
    import { ref, onMounted } from 'vue'
    import { useRouter } from 'vue-router'
    import { showToast, showConfirmDialog } from 'vant'
    import { orderListAPIRes, orderCanceAPIRes, orderDelAPIRes, orderFinishAPIRes } from '@/api'
    import { useOrder } from '@/store/order'

    const router = useRouter()
    const useorder = useOrder()
    const currentPage = ref(1)
    const loading = ref(false)
    const finished = ref(false)
    const refreshing = ref(false)
    const canceShow = ref(false)
    const canceItem = ref<any>({})
    const addClockShow = ref(false)
    const addClockItem = ref<any>({})
    const status = ref(0)
    const listData = ref<any>([])
    const refundDesc = ref('')
    const addClockActions = ref([
        {
            name: '加时长',
            callback: () => {
                router.push({
                    path: '/product/add',
                    query: { tid: addClockItem.value.tid, pid: addClockItem.value.pid, aid: addClockItem.value.aid, orderNo: addClockItem.value.orderNo, name: addClockItem.value.name, type: 1 }
                })
            }
        }, {
            name: '加项目',
            callback: async () => {
                router.push({
                    path: '/product/add',
                    query: { tid: addClockItem.value.tid, pid: addClockItem.value.pid, aid: addClockItem.value.aid, orderNo: addClockItem.value.orderNo, type: 2 }
                })
            }
        }
    ])

    const onLoad = async () => {
        loading.value = true
        const obj = {
            page: currentPage.value,
            status: status.value
        }
        const { data } = await orderListAPIRes(obj)
        if (refreshing.value) {
            listData.value = []
            refreshing.value = false
        }
        data.list.forEach((item: any) => {
            listData.value.push(item)
        })
        loading.value = false
        if (listData.value.length >= data.total) {
            finished.value = true
            currentPage.value = 1
        }
    }
    const onRefresh = () => {
        currentPage.value = 1
        listData.value = []
        finished.value = false
        refreshing.value = true
        loading.value = true
        onLoad()
    }
    // 加载下一页
    const nextPage = () => {
        loading.value = false
        currentPage.value += 1
        onLoad()
    }
    const onSearch = () => {
        currentPage.value = 1
        listData.value = []
        finished.value = false
        loading.value = true
        onLoad()
    }
    // 跳转订单详情
    const onToDetail = (orderNo: string) => {
        router.push({
            path: '/order/datail',
            query: { orderNo }
        })
    }
    // 删除订单
    const onDel = async (orderNo: string) => {
        showConfirmDialog({
            message: '是否确定删除此订单？',
            confirmButtonText: '是',
            cancelButtonText: '否'
        }).then(async () => {
            await orderDelAPIRes(orderNo)
            onRefresh()
        })
    }
    // 取消订单
    const onCanceShow = (item: any) => {
        canceItem.value = item
        refundDesc.value = ''
        canceShow.value = true
    }
    const onCance = async () => {
        const item = canceItem.value
        let msg = '是否确认取消此订单？'
        let refundAmount = item.totalAmount
        if (!item.associationOrderNo && item.orderType < 3 && (item.status == 3 && item.sallyPhoto || item.status == 4)) {
            msg = `技师已经${item.status == 4 ? '到达' : '出发'}，取消订单将扣取车费，是否确认取消此订单？`
            refundAmount = item.totalAmount - item.fareAmount
        }
        canceShow.value = false
        showConfirmDialog({
            message: msg,
            confirmButtonText: '是',
            cancelButtonText: '否'
        }).then(async () => {
            const obj = {
                orderNo: item.orderNo,
                associationOrderNo: item.associationOrderNo,
                refundDesc: refundDesc.value,
                refundAmount,
                totalAmount: item.totalAmount,
                fareAmount: item.fareAmount,
                status: item.status,
                tid: item.tid,
                productName: item.name,
                cid: item.cid
            }
            await orderCanceAPIRes(obj)
            onRefresh()
        })
    }
    // 修改项目
    const onUpdate = (tid: number, pid: number, aid: number, orderNo: string) => {
        router.push({
            path: '/product/edit',
            query: { tid, pid, aid, orderNo }
        })
    }
    // 加钟
    const onAddClock = (item: any) => {
        addClockItem.value = item
        addClockShow.value = true
    }
    // 完成订单
    const onFinish = (orderNo: string) => {
        showConfirmDialog({
            message: '是否确定结束此订单服务？',
            confirmButtonText: '是',
            cancelButtonText: '否'
        }).then(async () => {
            await orderFinishAPIRes({ orderNo })
            onRefresh()
        })
    }
    // 点击复制订单号
    const copyToClipboard = (orderNo: string) => {
        navigator.clipboard.writeText(orderNo).then(() => {
            showToast('复制成功')
        }).catch(err => {
            showToast('复制失败')
            console.log('复制失败', err)
        })
    }

    onMounted(() => {
        onLoad()
    })
</script>

<template>
    <van-tabs v-model:active="status" color="#7C6186" sticky @change="onSearch">
        <van-tab title="已下单" />
        <van-tab title="进行中" />
        <van-tab title="已取消" />
        <van-tab title="已完成" />
    </van-tabs>
    <van-pull-refresh v-model="refreshing" @refresh="onRefresh" class="pt-2.5" style="min-height: calc(100dvh - 50px - 44px);">
        <van-list v-if="listData.length > 0" v-model:loading="loading" :finished="finished" @load="nextPage">
            <div v-for="item in listData" :key="item.id" class="px-2.5 py-3 mx-2.5 mb-3 rounded-2xl bg-white" @click="onToDetail(item.orderNo)">
                <div class="flex items-center justify-between text-sm">
                    <div class="font-bold" @click.stop="copyToClipboard(item.orderNo)">订单号：{{ item.orderNo }}</div>
                    <div class="text-[#cd0505]">
                        <spna v-if="item.status == 1">待接单</spna>
                        <spna v-if="item.status == 2">已接单</spna>
                        <spna v-if="item.status == 3">已出发</spna>
                        <spna v-if="item.status == 4">已到达</spna>
                        <spna v-if="item.status == 5">服务中</spna>
                        <spna v-if="item.status > 5 && item.status < 30">服务完成</spna>
                        <spna v-if="item.status == 30">已取消</spna>
                    </div>
                </div>
                <div class="flex my-3">
                    <van-image
                        radius="0.625rem"
                        width="5.625rem"
                        height="5.625rem"
                        fit="cover"
                        :src="item.productImg"
                    />
                    <div class="flex-1 flex flex-col justify-between ml-3.5">
                        <div class="flex items-center justify-between text-sm font-bold text-[#333]">
                            <div>
                                <spna>{{ item.name }}</spna>
                                <spna v-if="item.orderType == 2">（改项目）</spna>
                                <spna v-if="item.orderType == 3">（时长加钟）</spna>
                                <spna v-if="item.orderType == 4">（项目加钟）</spna>
                            </div>
                            <div>
                                <span class="text-[0.625rem]">￥</span>
                                <span v-if="item.addTimeType == 1">80.00</span>
                                <span v-else-if="item.addTimeType == 2">100.00</span>
                                <span v-else-if="item.addTimeType == 3">120.00</span>
                                <span v-else>{{ (item.price || 0).toFixed(2) }}</span>
                            </div>
                        </div>
                        <div class="text-xs text-[#666]">服务技师：{{ item.nickname }}</div>
                        <div class="text-xs text-[#666]">服务时长：
                            <span v-if="item.addTimeType == 1">20分钟</span>
                            <span v-else-if="item.addTimeType == 2">30分钟</span>
                            <span v-else-if="item.addTimeType == 3">40分钟</span>
                            <span v-else>{{ item.duration }}分钟</span>
                        </div>
                        <div class="text-xs text-[#666]">{{ item.status == 30 ? '取消' : '下单' }}时间：{{ item.status == 30 ? item.cancelTime : item.createTime }}</div>
                    </div>
                </div>
                <div class="flex items-center justify-between">
                    <div class="text-sm font-bold text-[#333]">实付款：<span class="text-[0.625rem]">￥</span>{{ (item.totalAmount || 0).toFixed(2) }}</div>
                    <van-space>
                        <van-button v-if="item.status < 5" size="small" @click.stop="onCanceShow(item)">取消订单</van-button>
                        <van-button v-if="item.status > 5" size="small" @click.stop="onDel(item.orderNo)">删除订单</van-button>
                        <van-button v-if="item.status < 5 && item.orderType == 1" color="#7C6186" size="small" @click.stop="onUpdate(item.tid, item.pid, item.aid, item.orderNo)">改项目</van-button>
                        <van-button v-if="item.status == 5" color="#7C6186" size="small" @click.stop="onAddClock(item)">加钟</van-button>
                        <van-button v-if="item.status == 5" color="#7C6186" size="small" @click.stop="onFinish(item.orderNo)">服务完成</van-button>
                    </van-space>
                </div>
            </div>
        </van-list>
        <van-empty v-else image-size="100" description="暂无订单" />
    </van-pull-refresh>
    <!-- 取消弹窗 -->
    <van-popup v-model:show="canceShow" safe-area-inset-bottom round position="bottom" class="h-auto">
        <van-nav-bar title="取消订单" />
        <van-radio-group v-model="refundDesc">
            <van-cell-group inset :border="false">
                <van-cell v-for="(item, index) in useorder.refundDesc" ::key="index" :title="item" clickable :border="false" @click="refundDesc = item">
                    <template #right-icon>
                        <van-radio :name="item" checked-color="#7C6186" />
                    </template>
                </van-cell>
            </van-cell-group>
        </van-radio-group>
        <div class="flex items-center justify-between p-4">
            <van-button block round class="mr-2" @click="canceShow = false">暂不取消</van-button>
            <van-button block round class="ml-2" color="#7C6186" @click="onCance">确定取消</van-button>
        </div>
    </van-popup>
    <!-- 加钟选项 -->
    <van-action-sheet
        v-model:show="addClockShow"
        :actions="addClockActions"
        cancel-text="取消"
        close-on-click-action
        @cancel="addClockShow = false"
    />
</template>